package com.peng.kslc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A24SwapPairsListNodes
 * https://ssg.leetcode-cn.com/problems/swap-nodes-in-pairs/
 *
 * @author lupeng
 * Created on 2022-07-24
 */
public class A24SwapPairsListNodes {

    private static final Logger logger = LoggerFactory.getLogger(A24SwapPairsListNodes.class);

    public static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }
    }

    public static void main(String[] args) {
        //ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, null))));
        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, null)));
        ListNode listNode = new A24SwapPairsListNodes().swapPairs(head);
        System.out.println(listNode);
    }


    public ListNode swapPairs(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode sentry = new ListNode(-1);
        sentry.next = head;
        ListNode curr = sentry;

        ListNode left, right;
        left = right = head;
        int len = 0;
        while (right != null) {
            len++;
            right = right.next;
            if (len == 2) {
                curr.next = reverse(left, right);
                curr = left;
                left = right;
                len = 0;
            }
        }
        if (len > 0) {
            curr.next = left;
        }
        return sentry.next;
    }

    private ListNode reverse(ListNode head, ListNode tail) {
        ListNode pre = null;
        while (head != tail) {
            ListNode temp = head.next;
            head.next = pre;
            pre = head;
            head = temp;
        }
        return pre;
    }
}
